import type {MenuDataItem, Settings as LayoutSettings} from '@ant-design/pro-layout';
import {PageLoading, ProBreadcrumb, SettingDrawer} from '@ant-design/pro-layout';
import type {RunTimeLayoutConfig} from 'umi';
import {history} from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import {currentUser as queryCurrentUser} from './services/ant-design-pro/api';
import defaultSettings from '../config/defaultSettings';
import {fetchDataMenuList} from './services/ant-design-pro/menu';
import {IconMap} from 'antd/lib/result';


const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading/>,
};


function _mdate() {
  let d = new Date ().getTime ();
  let savdate1 = localStorage.getItem ( "movedate" ) || d

  let endtime1 = parseFloat ( String ( ((d - savdate1) / 1000 / 60) ) );
  // console.log(endtime1)
  return endtime1;
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  name?: string,
  avatar?: string,
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  menuList?: MenuDataItem[];
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  fetchMenuList?: () => Promise<MenuDataItem | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser ();
      // @ts-ignore
      return msg.data;
    } catch (error) {
      history.push ( loginPath );
    }
    return undefined;
  };
/*  const fetchMenuList = async () => {
    try {
      const msg = await fetchDataMenuList ();
      // @ts-ignore
      return msg.data;
    } catch (error) {
      history.push ( loginPath );
    }
    return undefined;
  };*/

  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {

    const currentUser = await fetchUserInfo ();
 //   const menuList = await fetchMenuList ();
    // var message = menuList.data;
    //  console.log ( currentUser );
    return {
      // avatar: currentUser?.avatarUrl,
      fetchUserInfo,
      currentUser: currentUser,
      settings: defaultSettings,
    //  menuList: menuList,
    };
  }
  const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] =>
    menus.map ( ({icon, routes, ...item}) => ({
      ...item,
      icon: icon && IconMap[icon as string],
      routes: routes && loopMenuItem ( routes ),
      query: {type: 1}
    }) );
  return {
    name: 'Serati Ma',
    avatar: 'https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqdXe4Ne7Gicp0gMxakdsA5sKhjS2DArficBA3icGZQmzaZXCGuxj3ukMiat9W7Wm4xUHsKENhTH2tkYQ/132',
  //  fetchMenuList,
    fetchUserInfo,
    settings: defaultSettings
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {

  document.addEventListener ( 'mousemove', (ev: MouseEvent) => {
    // console.log("mousedown")
    if (_mdate () > 15) {
      const {query} = history.location;
      localStorage.removeItem ( "token" )
      localStorage.removeItem ( "movedate" )
      const {redirect} = query as {
        redirect: string;
      };
      history.push ( redirect || '/user/login' );
    } else {
      localStorage.setItem ( "movedate", String ( new Date ().getTime () ) );
    }
  } )
  console.log ( initialState )
  return {
    iconfontUrl: '//at.alicdn.com/t/c/font_3624205_r2620klwtf.js',
    rightContentRender: () => <RightContent/>,
    disableContentMargin: false,
    waterMarkProps: {
      content: "Hello",
    },

    footerRender: () => <Footer/>,
    onPageChange: () => {
      const {location} = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push ( loginPath );
      }
    },

    menu: {

      locale: true,
      params: initialState,
     // loading: initialState?.menuList && initialState?.menuList.length > 0 ? false : true,
      request:  () => {

        return new Promise((resolve, reject) => {
          fetchDataMenuList().then(res=>{
            console.log(res)
            resolve(res.data)
          }).catch(e=>{
            reject([])
          })
        })
        // if (initialState?.menuList) {
        //   // console.log ( 'initialState.menuList', initialState?.menuList );
        //   return initialState?.menuList;
        // } else {
        //   return fetchDataMenuList ();
        // }
      },
    },
  // headerContentRender: () => <ProBreadcrumb />,
    breadcrumbRender: (routers = []) => [
      {
        path: '/',
        breadcrumbName: '主页',
      },
      ...routers,
    ],

    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      //   console.log(children);
      return (
        <>
          {children}
       {/*   {!props.location?.pathname?.includes ( '/login' ) && (
            <SettingDrawer
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState ( (preInitialState) => ({
                  ...preInitialState,
                  settings,
                }) );
              }}
            />
          )}*/}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/*export const request: RequestConfig = {

  headers: {
    Authorization: `${localStorage.getItem("token")}`,
  },
};*/
